package com.sense.cloud.coreservice.sdk.auth.filter;

import com.alibaba.fastjson.JSON;
import com.sense.cloud.coreservice.sdk.auth.modules.ChkResult;
import com.sense.cloud.coreservice.sdk.auth.modules.UserAppService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;






public abstract class AuthJaxrsFilter implements ContainerRequestFilter {
  private Logger log = LoggerFactory.getLogger(getClass());
  private UserAppService userAppService = new UserAppService();

  @Override
  public void filter(ContainerRequestContext request) throws IOException {
    String method = request.getMethod();
    UriInfo uriinfo = request.getUriInfo();
    String hosts = uriinfo.getBaseUri().toString();
    hosts = hosts.substring(0, hosts.length() - 1);
    // String action = uriinfo.getPath();
    String uri = uriinfo.getRequestUri().toString();

    if ("GET".equals(method)) {

      ChkResult res = userAppService.validateGet(uri);
      if ( !res.isResult() ) {
        String resStr = JSON.toJSONString(res);
        log.error("get " + resStr);
        request.abortWith(Response.status(401).header("Content-Type", 
            "application/json;charset=UTF-8").entity(resStr).build() );
      }

    } else if ("POST".equals(method)) {
      InputStream input = request.getEntityStream();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] bs = new byte[1024];
      int index = 0;
      
      if ( input != null ) {
        while ((index = input.read(bs)) > -1) {
          bos.write(bs, 0, index);
        }
      }
      
      byte[] b2 = bos.toByteArray();
      bos.flush();
      ByteArrayInputStream bis = new ByteArrayInputStream(b2);
      request.setEntityStream(bis);
      ChkResult res = userAppService.validatePost(uri, b2);
      if ( !res.isResult() ) {
        String resStr = JSON.toJSONString(res);
        log.error("post " + resStr);
        request.abortWith(Response.status(401).header("Content-Type", 
             "application/json;charset=UTF-8").entity(resStr).build());
      }
    }
  }

}
